package com.d3.sx_eprotection.controller;

import com.d3.sx_eprotection.common.util;
import com.d3.sx_eprotection.entity.Administrator;
import com.d3.sx_eprotection.entity.Grider;
import com.d3.sx_eprotection.entity.Supervisor;
import com.d3.sx_eprotection.service.AdministratorService;
import com.d3.sx_eprotection.service.GriderService;
import com.d3.sx_eprotection.service.SupervisorService;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@RestController
public class LoginController {
    @Resource
    SupervisorService service;
    @Resource
    GriderService griderService;
    @Resource AdministratorService administratorService;
    //登录
    @PostMapping("/supervisor_login")
    public Map<String, Object> login(@RequestBody Supervisor supervisor) {
        //登录时，对用户传入的密码进行MD5加密
        String md5Hex = DigestUtils.md5DigestAsHex(supervisor.getPassword().getBytes());
        supervisor.setPassword(md5Hex);
        Map<String, Object> map=service.login(supervisor);
        if ((Boolean) map.get("status")){
            Supervisor allmesg = new Supervisor(service.getById(supervisor.getPhoneNumber()));
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(allmesg.getBirthday(),formatter);
            LocalDate current = LocalDate.now();
            int age = util.calculateAge(date,current);
            allmesg.setAge(age);
            service.updateById(allmesg);
        }
        return map;
    }
    @PostMapping("/grider_login")
    public Map<String,Object> gLogin(@RequestBody Grider grider){
        String md5Hex = DigestUtils.md5DigestAsHex(grider.getPassword().getBytes());
        grider.setPassword(md5Hex);
        Map<String, Object> map=griderService.login(grider);
        return map;
    }

    @PostMapping ("/Administrator_login")
    public Map<String,Object> ALogin(@RequestBody Administrator administrator){
        String md5Hex = DigestUtils.md5DigestAsHex(administrator.getPassword().getBytes());
        administrator.setPassword(md5Hex);
        Map<String, Object> map= administratorService.login(administrator);
        return map;
    }
}
